// 微信支付方法路径自行修改成自己的
const userModel = appRequire('models/user');
const orderModel = appRequire('models/order');

const { transfers } = require('./transfers')
const { createOrderNumber } = require('./payUtil')

module.exports = {
    wxOutMoney
};

//微信支付
async function wxOutMoney(req, thisResponse) {
    const returnData = Common.clone(Constant.DEFAULT_SUCCESS);
    let postData = req.body;

    let checkResult = Common.checkUrl(postData, ['openid', 'uid'], thisResponse);
    if (checkResult == false) return;

    let userResult = await userModel.user.findOne({
        where: {
            objectId: postData.uid,
            wcMiniId: postData.openid,
        }
    })
    userResult = Common.clone(userResult)

    if (userResult) {
        if (userResult.mobilePhoneNumber == "" || userResult.mobilePhoneNumber == null) {
            returnData.code = 0
            returnData.msg = "请绑定手机号"
            return thisResponse.json(returnData)
        }
        if (postData.outMoney <= 0) {
            returnData.code = 0
            returnData.msg = "提现金额有误"
            return thisResponse.json(returnData)
        }

        if (postData.outMoney > userResult.storeMoney) {
            returnData.code = 0
            returnData.msg = "超过可提现金额"
            return thisResponse.json(returnData)
        }

        console.log(req.connection.remoteAddress)

        let out_trade_no = createOrderNumber()
        let map = {
            // 金额
            amount: postData.outMoney,
            // 备注
            desc: '提现',
            // 用户openid
            openid: postData.openid,
            // 系统内部流水号
            recordId: out_trade_no,
            ip: req.connection.remoteAddress
        }
        try {
            let result = await transfers(map)

            let thisResult = await userModel.user.update({
                storeMoney: Number(userResult.storeMoney) - Number(postData.outMoney)
            }, {
                where: {
                    objectId: postData.uid,
                    wcMiniId: postData.openid,
                }
            })

            await orderModel.order.create({
                objectId: sid.uuid(),
                out_trade_no: out_trade_no,
                status: 1,
                sellerId: postData.uid,
                payMoney: Number(postData.outMoney),
                storeMoney: Number(postData.outMoney),
                type: -1,
            })

            returnData.data = thisResult
            return thisResponse.json(returnData)
        } catch (err) {
            returnData.code = 0
            returnData.msg = err.msg
            return thisResponse.json(returnData)
        }
    } else {
        returnData.code = 0
        returnData.msg = "请联系客服"
        return thisResponse.json(returnData)
    }


}

